{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "view-in-github"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W1D5_DimensionalityReduction/student/W1D5_Tutorial1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "# Neuromatch Academy: Week 1, Day 5, Tutorial 1\n",
    "# Dimensionality Reduction: Geometric view of data\n",
    "\n",
    "__Content creators:__ Alex Cayco Gajic, John Murray\n",
    "\n",
    "__Content reviewers:__ Roozbeh Farhoudi, Matt Krause, Spiros Chavlis, Richard Gao, Michael Waskom\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "---\n",
    "# Tutorial Objectives\n",
    "\n",
    "In this notebook we'll explore how multivariate data can be represented in different orthonormal bases. This will help us build intuition that will be helpful in understanding PCA in the following tutorial. \n",
    "\n",
    "Overview:\n",
    " - Generate correlated multivariate data.\n",
    " - Define an arbitrary orthonormal basis. \n",
    " - Project the data onto the new basis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 518
    },
    "colab_type": "code",
    "outputId": "27407ec9-f67e-4c34-e75a-a009b843af83"
   },
   "outputs": [],
   "source": [
    "# @title Video 1: Geometric view of data\n",
    "from IPython.display import YouTubeVideo\n",
    "video = YouTubeVideo(id=\"THu9yHnpq9I\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "---\n",
    "# Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# Import\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {},
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# @title Figure Settings\n",
    "import ipywidgets as widgets  # interactive display\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "plt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {},
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# @title Helper functions\n",
    "\n",
    "\n",
    "def get_data(cov_matrix):\n",
    "  \"\"\"\n",
    "  Returns a matrix of 1000 samples from a bivariate, zero-mean Gaussian.\n",
    "\n",
    "  Note that samples are sorted in ascending order for the first random variable\n",
    "\n",
    "  Args:\n",
    "    cov_matrix (numpy array of floats): desired covariance matrix\n",
    "\n",
    "  Returns:\n",
    "    (numpy array of floats) : samples from the bivariate Gaussian, with each\n",
    "                              column corresponding to a different random\n",
    "                              variable\n",
    "  \"\"\"\n",
    "\n",
    "  mean = np.array([0, 0])\n",
    "  X = np.random.multivariate_normal(mean, cov_matrix, size=1000)\n",
    "  indices_for_sorting = np.argsort(X[:, 0])\n",
    "  X = X[indices_for_sorting, :]\n",
    "\n",
    "  return X\n",
    "\n",
    "\n",
    "def plot_data(X):\n",
    "  \"\"\"\n",
    "  Plots bivariate data. Includes a plot of each random variable, and a scatter\n",
    "  plot of their joint activity. The title indicates the sample correlation\n",
    "  calculated from the data.\n",
    "\n",
    "  Args:\n",
    "    X (numpy array of floats) :   Data matrix each column corresponds to a\n",
    "                                  different random variable\n",
    "\n",
    "  Returns:\n",
    "    Nothing.\n",
    "  \"\"\"\n",
    "\n",
    "  fig = plt.figure(figsize=[8, 4])\n",
    "  gs = fig.add_gridspec(2, 2)\n",
    "  ax1 = fig.add_subplot(gs[0, 0])\n",
    "  ax1.plot(X[:, 0], color='k')\n",
    "  plt.ylabel('Neuron 1')\n",
    "  plt.title('Sample var 1: {:.1f}'.format(np.var(X[:, 0])))\n",
    "  ax1.set_xticklabels([])\n",
    "  ax2 = fig.add_subplot(gs[1, 0])\n",
    "  ax2.plot(X[:, 1], color='k')\n",
    "  plt.xlabel('Sample Number')\n",
    "  plt.ylabel('Neuron 2')\n",
    "  plt.title('Sample var 2: {:.1f}'.format(np.var(X[:, 1])))\n",
    "  ax3 = fig.add_subplot(gs[:, 1])\n",
    "  ax3.plot(X[:, 0], X[:, 1], '.', markerfacecolor=[.5, .5, .5],\n",
    "           markeredgewidth=0)\n",
    "  ax3.axis('equal')\n",
    "  plt.xlabel('Neuron 1 activity')\n",
    "  plt.ylabel('Neuron 2 activity')\n",
    "  plt.title('Sample corr: {:.1f}'.format(np.corrcoef(X[:, 0], X[:, 1])[0, 1]))\n",
    "  plt.show()\n",
    "\n",
    "\n",
    "def plot_basis_vectors(X, W):\n",
    "  \"\"\"\n",
    "  Plots bivariate data as well as new basis vectors.\n",
    "\n",
    "  Args:\n",
    "    X (numpy array of floats) :   Data matrix each column corresponds to a\n",
    "                                  different random variable\n",
    "    W (numpy array of floats) :   Square matrix representing new orthonormal\n",
    "                                  basis each column represents a basis vector\n",
    "\n",
    "  Returns:\n",
    "    Nothing.\n",
    "  \"\"\"\n",
    "\n",
    "  plt.figure(figsize=[4, 4])\n",
    "  plt.plot(X[:, 0], X[:, 1], '.', color=[.5, .5, .5], label='Data')\n",
    "  plt.axis('equal')\n",
    "  plt.xlabel('Neuron 1 activity')\n",
    "  plt.ylabel('Neuron 2 activity')\n",
    "  plt.plot([0, W[0, 0]], [0, W[1, 0]], color='r', linewidth=3,\n",
    "           label='Basis vector 1')\n",
    "  plt.plot([0, W[0, 1]], [0, W[1, 1]], color='b', linewidth=3,\n",
    "           label='Basis vector 2')\n",
    "  plt.legend()\n",
    "  plt.show()\n",
    "\n",
    "\n",
    "def plot_data_new_basis(Y):\n",
    "  \"\"\"\n",
    "  Plots bivariate data after transformation to new bases.\n",
    "  Similar to plot_data but with colors corresponding to projections onto\n",
    "  basis 1 (red) and basis 2 (blue). The title indicates the sample correlation\n",
    "  calculated from the data.\n",
    "\n",
    "  Note that samples are re-sorted in ascending order for the first\n",
    "  random variable.\n",
    "\n",
    "  Args:\n",
    "    Y (numpy array of floats):   Data matrix in new basis each column\n",
    "                                 corresponds to a different random variable\n",
    "\n",
    "  Returns:\n",
    "    Nothing.\n",
    "  \"\"\"\n",
    "  fig = plt.figure(figsize=[8, 4])\n",
    "  gs = fig.add_gridspec(2, 2)\n",
    "  ax1 = fig.add_subplot(gs[0, 0])\n",
    "  ax1.plot(Y[:, 0], 'r')\n",
    "  plt.xlabel\n",
    "  plt.ylabel('Projection \\n basis vector 1')\n",
    "  plt.title('Sample var 1: {:.1f}'.format(np.var(Y[:, 0])))\n",
    "  ax1.set_xticklabels([])\n",
    "  ax2 = fig.add_subplot(gs[1, 0])\n",
    "  ax2.plot(Y[:, 1], 'b')\n",
    "  plt.xlabel('Sample number')\n",
    "  plt.ylabel('Projection \\n basis vector 2')\n",
    "  plt.title('Sample var 2: {:.1f}'.format(np.var(Y[:, 1])))\n",
    "  ax3 = fig.add_subplot(gs[:, 1])\n",
    "  ax3.plot(Y[:, 0], Y[:, 1], '.', color=[.5, .5, .5])\n",
    "  ax3.axis('equal')\n",
    "  plt.xlabel('Projection basis vector 1')\n",
    "  plt.ylabel('Projection basis vector 2')\n",
    "  plt.title('Sample corr: {:.1f}'.format(np.corrcoef(Y[:, 0], Y[:, 1])[0, 1]))\n",
    "  plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "---\n",
    "# Section 1: Generate correlated multivariate data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 518
    },
    "colab_type": "code",
    "outputId": "e261f31b-a238-4dde-e14a-4ee8dfb23aac"
   },
   "outputs": [],
   "source": [
    "# @title Video 2: Multivariate data\n",
    "video = YouTubeVideo(id=\"jcTq2PgU5Vw\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "To gain intuition, we will first use a simple model to generate multivariate data. Specifically, we will draw random samples from a *bivariate normal distribution*. This is an extension of the one-dimensional normal distribution to two dimensions, in which each $x_i$ is marginally normal with mean $\\mu_i$ and variance $\\sigma_i^2$:\n",
    "\n",
    "\\begin{align}\n",
    "x_i \\sim \\mathcal{N}(\\mu_i,\\sigma_i^2).\n",
    "\\end{align}\n",
    "\n",
    "Additionally, the joint distribution for $x_1$ and $x_2$ has a specified correlation coefficient $\\rho$. Recall that the correlation coefficient is a normalized version of the covariance, and ranges between -1 and +1:\n",
    "\n",
    "\\begin{align}\n",
    "\\rho = \\frac{\\text{cov}(x_1,x_2)}{\\sqrt{\\sigma_1^2 \\sigma_2^2}}.\n",
    "\\end{align}\n",
    "\n",
    "For simplicity, we will assume that the mean of each variable has already been subtracted, so that $\\mu_i=0$. The remaining parameters can be summarized in the covariance matrix, which for two dimensions has the following form:\n",
    "\n",
    "\\begin{equation*}\n",
    "{\\bf \\Sigma} = \n",
    "\\begin{pmatrix}\n",
    " \\text{var}(x_1) & \\text{cov}(x_1,x_2) \\\\\n",
    " \\text{cov}(x_1,x_2) &\\text{var}(x_2)\n",
    "\\end{pmatrix}.\n",
    "\\end{equation*}\n",
    "\n",
    "In general, $\\bf \\Sigma$ is a symmetric matrix with the variances $\\text{var}(x_i) = \\sigma_i^2$ on the diagonal, and the covariances on the off-diagonal. Later, we will see that the covariance matrix plays a key role in PCA.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "\n",
    "## Exercise 1: Draw samples from a distribution\n",
    "\n",
    "We have provided code to draw random samples from a zero-mean bivariate normal distribution. Throughout this tutorial, we'll imagine these samples represent the activity (firing rates) of two recorded neurons on different trials. Fill in the function below to calculate the covariance matrix given the desired variances and correlation coefficient. The covariance can be found by rearranging the equation above:\n",
    "\n",
    "\\begin{align}\n",
    "\\text{cov}(x_1,x_2) = \\rho \\sqrt{\\sigma_1^2 \\sigma_2^2}.\n",
    "\\end{align}\n",
    "\n",
    "Use these functions to generate and plot data while varying the parameters. You should get a feel for how changing the correlation coefficient affects the geometry of the simulated data.\n",
    "\n",
    "**Steps**\n",
    "* Fill in the function `calculate_cov_matrix` to calculate the desired covariance.\n",
    "* Generate and plot the data for $\\sigma_1^2 =1$, $\\sigma_1^2 =1$, and $\\rho = .8$. Try plotting the data for different values of the correlation coefficent: $\\rho = -1, -.5, 0, .5, 1$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 514
    },
    "colab_type": "code",
    "outputId": "62dc3b47-bdec-445a-e8b8-2335f2793419"
   },
   "outputs": [],
   "source": [
    "help(plot_data)\n",
    "help(get_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "def calculate_cov_matrix(var_1, var_2, corr_coef):\n",
    "  \"\"\"\n",
    "  Calculates the covariance matrix based on the variances and correlation\n",
    "  coefficient.\n",
    "\n",
    "  Args:\n",
    "    var_1 (scalar)          : variance of the first random variable\n",
    "    var_2 (scalar)          : variance of the second random variable\n",
    "    corr_coef (scalar)      : correlation coefficient\n",
    "\n",
    "  Returns:\n",
    "    (numpy array of floats) : covariance matrix\n",
    "  \"\"\"\n",
    "\n",
    "  #################################################\n",
    "  ## TODO for students: calculate the covariance matrix\n",
    "  # Fill out function and remove\n",
    "  raise NotImplementedError(\"Student excercise: calculate the covariance matrix!\")\n",
    "  #################################################\n",
    "\n",
    "  # Calculate the covariance from the variances and correlation\n",
    "  cov = ...\n",
    "\n",
    "  cov_matrix = np.array([[var_1, cov], [cov, var_2]])\n",
    "\n",
    "  return cov_matrix\n",
    "\n",
    "\n",
    "###################################################################\n",
    "## TO DO for students: generate and plot bivariate Gaussian data with variances of 1\n",
    "## and a correlation coefficients of: 0.8\n",
    "## repeat while varying the correlation coefficient from -1 to 1\n",
    "###################################################################\n",
    "np.random.seed(2020)  # set random seed\n",
    "variance_1 = 1\n",
    "variance_2 = 1\n",
    "corr_coef = 0.8\n",
    "\n",
    "# Uncomment to test your code and plot\n",
    "# cov_matrix = calculate_cov_matrix(variance_1, variance_2, corr_coef)\n",
    "# X = get_data(cov_matrix)\n",
    "# plot_data(X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 289
    },
    "colab_type": "text",
    "outputId": "87407e56-4bd4-4cf0-d040-57381772daad"
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial1_Solution_a068bc84.py)\n",
    "\n",
    "*Example output:*\n",
    "\n",
    "<img alt='Solution hint' align='left' width=570 height=272 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W1D5_DimensionalityReduction/static/W1D5_Tutorial1_Solution_a068bc84_0.png>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "---\n",
    "# Section 2: Define a new orthonormal basis\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 518
    },
    "colab_type": "code",
    "outputId": "0abeabea-176c-4238-c3cc-779400e67617"
   },
   "outputs": [],
   "source": [
    "# @title Video 3: Orthonormal bases\n",
    "video = YouTubeVideo(id=\"PC1RZELnrIg\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Next, we will define a new orthonormal basis of vectors ${\\bf u} = [u_1,u_2]$ and ${\\bf w} = [w_1,w_2]$. As we learned in the video, two vectors are orthonormal if: \n",
    "\n",
    "1.   They are orthogonal (i.e., their dot product is zero):\n",
    "\\begin{equation}\n",
    "{\\bf u\\cdot w} = u_1 w_1 + u_2 w_2 = 0\n",
    "\\end{equation}\n",
    "2.   They have unit length:\n",
    "\\begin{equation}\n",
    "||{\\bf u} || = ||{\\bf w} || = 1\n",
    "\\end{equation}\n",
    "\n",
    "In two dimensions, it is easy to make an arbitrary orthonormal basis. All we need is a random vector ${\\bf u}$, which we have normalized. If we now define the second basis vector to be ${\\bf w} = [-u_2,u_1]$, we can check that both conditions are satisfied: \n",
    "\\begin{equation}\n",
    "{\\bf u\\cdot w} = - u_1 u_2 + u_2 u_1 = 0\n",
    "\\end{equation}\n",
    "and \n",
    "\\begin{equation}\n",
    "{|| {\\bf w} ||} = \\sqrt{(-u_2)^2 + u_1^2} = \\sqrt{u_1^2 + u_2^2} = 1,\n",
    "\\end{equation}\n",
    "where we used the fact that ${\\bf u}$ is normalized. So, with an arbitrary input vector, we can define an orthonormal basis, which we will write in matrix by stacking the basis vectors horizontally:\n",
    "\n",
    "\\begin{equation}\n",
    "{{\\bf W} } =\n",
    "\\begin{pmatrix}\n",
    " u_1 & w_1 \\\\\n",
    " u_2 & w_2\n",
    "\\end{pmatrix}.\n",
    "\\end{equation}\n",
    "\n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Exercise 2: Find an orthonormal basis\n",
    "\n",
    "In this exercise you will fill in the function below to define an orthonormal basis, given a single arbitrary 2-dimensional vector as an input.\n",
    "\n",
    "**Steps**\n",
    "* Modify the function `define_orthonormal_basis` to first normalize the first basis vector $\\bf u$.\n",
    "* Then complete the function by finding a basis vector $\\bf w$ that is orthogonal to $\\bf u$.\n",
    "* Test the function using initial basis vector ${\\bf u} = [3,1]$. Plot the resulting basis vectors on top of the data scatter plot using the function `plot_basis_vectors`. (For the data, use  $\\sigma_1^2 =1$, $\\sigma_2^2 =1$, and $\\rho = .8$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 257
    },
    "colab_type": "code",
    "outputId": "875de345-7eb6-4a82-a05f-eedb5926e91f"
   },
   "outputs": [],
   "source": [
    "help(plot_basis_vectors)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "def define_orthonormal_basis(u):\n",
    "  \"\"\"\n",
    "  Calculates an orthonormal basis given an arbitrary vector u.\n",
    "\n",
    "  Args:\n",
    "    u (numpy array of floats) : arbitrary 2-dimensional vector used for new\n",
    "                                basis\n",
    "\n",
    "  Returns:\n",
    "    (numpy array of floats)   : new orthonormal basis\n",
    "                                columns correspond to basis vectors\n",
    "  \"\"\"\n",
    "\n",
    "  #################################################\n",
    "  ## TODO for students: calculate the orthonormal basis\n",
    "  # Fill out function and remove\n",
    "  raise NotImplementedError(\"Student excercise: implement the orthonormal basis function\")\n",
    "  #################################################\n",
    "\n",
    "  # normalize vector u\n",
    "  u = ...\n",
    "  # calculate vector w that is orthogonal to w\n",
    "  w = ...\n",
    "\n",
    "  W = np.column_stack([u, w])\n",
    "\n",
    "  return W\n",
    "\n",
    "\n",
    "np.random.seed(2020)  # set random seed\n",
    "variance_1 = 1\n",
    "variance_2 = 1\n",
    "corr_coef = 0.8\n",
    "\n",
    "cov_matrix = calculate_cov_matrix(variance_1, variance_2, corr_coef)\n",
    "X = get_data(cov_matrix)\n",
    "u = np.array([3, 1])\n",
    "\n",
    "# Uncomment and run below to plot the basis vectors\n",
    "# W = define_orthonormal_basis(u)\n",
    "# plot_basis_vectors(X, W)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 289
    },
    "colab_type": "text",
    "outputId": "692ac8a7-45b5-4a00-ad38-4522f4c0ecdd"
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial1_Solution_85e5b50f.py)\n",
    "\n",
    "*Example output:*\n",
    "\n",
    "<img alt='Solution hint' align='left' width=274 height=272 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W1D5_DimensionalityReduction/static/W1D5_Tutorial1_Solution_85e5b50f_0.png>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "---\n",
    "# Section 3: Project data onto new basis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 518
    },
    "colab_type": "code",
    "outputId": "7b73ce6c-60a2-447d-84d6-d67204979afe"
   },
   "outputs": [],
   "source": [
    "# @title Video 4: Change of basis\n",
    "video = YouTubeVideo(id=\"Mj6BRQPKKUc\", width=854, height=480, fs=1)\n",
    "print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n",
    "video"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "\n",
    "   \n",
    "Finally, we will express our data in the new basis that we have just found. Since $\\bf W$ is orthonormal, we can project the data into our new basis using simple matrix multiplication :\n",
    "\n",
    "\\begin{equation}\n",
    "{\\bf Y = X W}.\n",
    "\\end{equation}\n",
    "\n",
    "We will explore the geometry of the transformed data $\\bf Y$ as we vary the choice of basis."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Exercise 3: Define an orthonormal basis\n",
    "In this exercise you will fill in the function below to define an orthonormal basis, given a single arbitrary vector as an input.\n",
    "\n",
    "**Steps**\n",
    "* Complete the function `change_of_basis` to project the data onto the new basis.\n",
    "* Plot the projected data using the function `plot_data_new_basis`. \n",
    "* What happens to the correlation coefficient in the new basis? Does it increase or decrease? \n",
    "* What happens to variance? \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "def change_of_basis(X, W):\n",
    "  \"\"\"\n",
    "  Projects data onto new basis W.\n",
    "\n",
    "  Args:\n",
    "    X (numpy array of floats) : Data matrix each column corresponding to a\n",
    "                                different random variable\n",
    "    W (numpy array of floats) : new orthonormal basis columns correspond to\n",
    "                                basis vectors\n",
    "\n",
    "  Returns:\n",
    "    (numpy array of floats)    : Data matrix expressed in new basis\n",
    "  \"\"\"\n",
    "\n",
    "  #################################################\n",
    "  ## TODO for students: project the data onto o new basis W\n",
    "  # Fill out function and remove\n",
    "  raise NotImplementedError(\"Student excercise: implement change of basis\")\n",
    "  #################################################\n",
    "\n",
    "  # project data onto new basis described by W\n",
    "  Y = ...\n",
    "\n",
    "  return Y\n",
    "\n",
    "\n",
    "# Unomment below to transform the data by projecting it into the new basis\n",
    "# Y = change_of_basis(X, W)\n",
    "# plot_data_new_basis(Y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 289
    },
    "colab_type": "text",
    "outputId": "6ae7008b-0f5c-4d43-eb19-45787a995387"
   },
   "source": [
    "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial1_Solution_a1124bbc.py)\n",
    "\n",
    "*Example output:*\n",
    "\n",
    "<img alt='Solution hint' align='left' width=560 height=272 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W1D5_DimensionalityReduction/static/W1D5_Tutorial1_Solution_a1124bbc_0.png>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Interactive Demo: Play with the basis vectors\n",
    "To see what happens to the correlation as we change the basis vectors, run the cell below. The parameter $\\theta$ controls the angle of $\\bf u$ in degrees. Use the slider to rotate the basis vectors. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 588,
     "referenced_widgets": [
      "103182f1916b4aab81d4444e690d15a3",
      "8770c3fad5af4ae98f6b19c1cd15f6b6",
      "f3ae30ce068f4e37823bc82cea26ca32",
      "724721c3b71842fa863c727fa8ab2d9f",
      "f231860ae93845129fc2280eecd09aeb",
      "80a7274133094fcab8370a06f03b0ab5",
      "8b23c192ec1c49468b0949104c242257"
     ]
    },
    "colab_type": "code",
    "outputId": "657b6946-a7aa-4a4d-b57c-ee4eba1eac0c"
   },
   "outputs": [],
   "source": [
    "# @title\n",
    "\n",
    "# @markdown Make sure you execute this cell to enable the widget!\n",
    "\n",
    "\n",
    "def refresh(theta=0):\n",
    "  u = [1, np.tan(theta * np.pi / 180)]\n",
    "  W = define_orthonormal_basis(u)\n",
    "  Y = change_of_basis(X, W)\n",
    "  plot_basis_vectors(X, W)\n",
    "  plot_data_new_basis(Y)\n",
    "\n",
    "\n",
    "_ = widgets.interact(refresh, theta=(0, 90, 5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Questions\n",
    "\n",
    "* What happens to the projected data as you rotate the basis? \n",
    "* How does the correlation coefficient change? How does the variance of the projection onto each basis vector change?\n",
    "* Are you able to find a basis in which the projected data is **uncorrelated**?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "---\n",
    "# Summary\n",
    "\n",
    "- In this tutorial, we learned that multivariate data can be visualized as a cloud of points in a high-dimensional vector space. The geometry of this cloud is shaped by the covariance matrix.\n",
    "\n",
    "- Multivariate data can be represented in a new orthonormal basis using the dot product. These new basis vectors correspond to specific mixtures of the original variables - for example, in neuroscience, they could represent different ratios of activation  across a population of neurons.\n",
    "\n",
    "- The projected data (after transforming into the new basis) will generally have a different geometry from the original data. In particular, taking basis vectors that are aligned with the spread of cloud of points decorrelates the data.\n",
    "\n",
    "* These concepts - covariance, projections, and orthonormal bases - are key for understanding PCA, which we be our focus in the next tutorial."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "include_colab_link": true,
   "name": "W1D5_Tutorial1",
   "provenance": [],
   "toc_visible": true
  },
  "kernel": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
